package ldkxingzhe.l365calendar.widget.dialog.picker;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Date;

import ldkxingzhe.l365calendar.R;
import ldkxingzhe.l365calendar.utils.CalendarUtil;
import ldkxingzhe.l365calendar.utils.LunarHelper;
import ldkxingzhe.l365calendar.utils.OSUtil;
import ldkxingzhe.l365calendar.widget.dialog.DialogFragmentBase;
import ldkxingzhe.l365calendar.widget.wheelview.OnWheelChangedListener;
import ldkxingzhe.l365calendar.widget.wheelview.WheelView;
import ldkxingzhe.l365calendar.widget.wheelview.adapter.NumericWheelAdapter;

/**
 * 时间的拾取器　
 * Created by ke on 16-1-26.
 */
public class DatePicker extends DialogFragmentBase {
    @SuppressWarnings("unused")
    private static final String TAG = "DatePicker";

    public static final String RESULT = "result";
    protected static final String TIME = "time";

    protected WheelView year, month, day;
    protected NumericWheelAdapter yearAdapter, monthAdapter, dayAdapter;
    protected Calendar time;
    protected TextView title;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View resultView = inflater.inflate(R.layout.picker_date_layout, container, false);
        year = (WheelView) resultView.findViewById(R.id.year);
        month = (WheelView) resultView.findViewById(R.id.month);
        day = (WheelView) resultView.findViewById(R.id.day);
        title = (TextView) resultView.findViewById(R.id.title);
        initYMDAdapter();
        initButtonLayout(resultView.findViewById(R.id.button_layout));
        if(time != null){
            initYMD();
        }
        return resultView;
    }
    // 初始化年月日
    protected void initYMD() {
        setYear(time.get(Calendar.YEAR));
        setMonth(time.get(Calendar.MONTH) + 1);
        setDay(time.get(Calendar.DAY_OF_MONTH));
    }

    /**
     * 实例化
     * @param milliseconds    毫秒
     * @return
     */
    public static DatePicker newInstance(long milliseconds) {

        if(milliseconds <= 0) milliseconds = new Date().getTime();
        Bundle args = new Bundle();
        args.putLong(TIME, milliseconds);
        DatePicker fragment = new DatePicker();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        if(args == null) return;
        long timeLong = args.getLong(TIME);
        if(timeLong <= 0) timeLong = new Date().getTime();
        time = Calendar.getInstance();
        time.setTimeInMillis(timeLong);
    }

    protected void initButtonLayout(View buttonLayout) {
        TextView negativeButton = (TextView) buttonLayout.findViewById(R.id.negative_button);
        TextView positiveButton = (TextView) buttonLayout.findViewById(R.id.positive_button);
        negativeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismissAndDealWithResult(Activity.RESULT_CANCELED, new Intent());
            }
        });

        positiveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra(RESULT, getResult());
                dismissAndDealWithResult(Activity.RESULT_OK, intent);
            }
        });
    }

    protected String getResult(){
        DecimalFormat format = new DecimalFormat("00");
        return getYear() + "-" + format.format(getMonth()) + "-" + format.format(getDay());
    }


    protected void initYMDAdapter() {
        yearAdapter = new NumericWheelAdapter(getActivity(), 1900, 2100);
        monthAdapter = new NumericWheelAdapter(getActivity(), 1, 12);
        dayAdapter = new NumericWheelAdapter(getActivity(), 1, 31);

        yearAdapter.setLabel("年");
        monthAdapter.setLabel("月");
        dayAdapter.setLabel("日");

        setTextSizeAndColor(yearAdapter);
        setTextSizeAndColor(monthAdapter);
        setTextSizeAndColor(dayAdapter);

        year.setViewAdapter(yearAdapter);
        month.setViewAdapter(monthAdapter);
        day.setViewAdapter(dayAdapter);

        month.setCyclic(true);
        day.setCyclic(true);
        year.setCyclic(false);

        year.addChangingListener(yearMonthListener);
        day.addChangingListener(dayListener);
        month.addChangingListener(yearMonthListener);
    }

    protected void setTextSizeAndColor(NumericWheelAdapter adapter) {
        adapter.setTextSize((int) OSUtil.dp2px(10));
        adapter.setTextColor(Color.BLACK);
    }

    private OnWheelChangedListener yearMonthListener = new OnWheelChangedListener() {
        @Override
        public void onChanged(WheelView wheel, int oldValue, int newValue) {
            int yearNumber = getYear();
            int monthNumber = getMonth();
            dayAdapter.setMaxValue(CalendarUtil.getDayCount(yearNumber, monthNumber));
            day.invalidateWheel(true);
            notifyDateChanged();
        }
    };

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        strArray = getResources().getStringArray(R.array.week_names);
    }

    String[] strArray;
    private void notifyDateChanged() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(getYear(), getMonth() - 1, getDay());
        Log.v(TAG, "notifyDateChanged, and time is " + CalendarUtil.formatTime(calendar.getTimeInMillis(), CalendarUtil.DATE));
        StringBuilder builder = new StringBuilder();
        LunarHelper helper = new LunarHelper(calendar);
        builder.append(getString(R.string.lunar) + ":");
        builder.append(helper.getLunarDate());
        builder.append("   ");
        if(DateUtils.isToday(calendar.getTimeInMillis())){
            builder.append("今天");
        }else{
            int index = calendar.get(Calendar.DAY_OF_WEEK) - 2;
            if(index == -1) index = 6;
            builder.append("周" + strArray[index]);
        }
        title.setText(builder.toString());
    }

    protected int getYear(){
        return year.getCurrentItem() + 1900;
    }
    protected void setYear(int yy){
        year.setCurrentItem(yy - 1900);
    }
    protected int getMonth(){
        return month.getCurrentItem() + 1;
    }
    protected void setMonth(int mm){
        month.setCurrentItem(mm - 1);
    }
    protected int getDay(){
        return day.getCurrentItem() + 1;
    }
    protected void setDay(int dd){
        day.setCurrentItem(dd - 1);
    }

    private OnWheelChangedListener dayListener = new OnWheelChangedListener() {
        @Override
        public void onChanged(WheelView wheel, int oldValue, int newValue) {
            Log.v(TAG, "dayListener");
            notifyDateChanged();
        }
    };
}
